package com.zodiac.app.gsps.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

public class DataSourceHelper {

    public static DataSource createDataSource() {
        return new DruidDataSource();
    }

    public static DataSourceTransactionManager createDataSourceTransactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    public static SqlSessionFactory createSqlSessionFactory(DataSource dataSource, String mapperLocationPattern) {
        try {
            SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
            sf.setDataSource(dataSource);
            sf.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocationPattern));
            // 设置MyBatis分页插件
            PageInterceptor pageInterceptor = new PageInterceptor();
            Properties properties = new Properties();
            properties.setProperty("helperDialect", "mysql");
            pageInterceptor.setProperties(properties);
            sf.setPlugins(new Interceptor[]{pageInterceptor});
            // 设置默认属性
            org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
            configuration.setCallSettersOnNulls(true);
            sf.setConfiguration(configuration);
            return sf.getObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
